<template>
  <div style="padding-bottom: 60px;">
    <h3>
      项目任务推进表
    </h3>
    <div style="margin-top: 16px;width: 100%;">
      <Form inline ref="formInline">
        <FormItem>
          <DatePicker v-width="180" v-model="params.date" type="month" placeholder="选择月份" @on-change="changeParams"
            :clearable="false">
          </DatePicker>
        </FormItem>
        <FormItem>
          <Select v-model="params.department" v-width="180" placeholder="选择部门" @on-change="changeParams" clearable>
            <Option v-for="(item,index) in departmentList" :key="index" :value="item.value">{{item.label}}</Option>
          </Select>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="exportData">导出</Button>
        </FormItem>
      </Form>
      <template>
        <ux-grid :show-summary="true" :summary-method="allFun" :key="reset" border show-overflow ref="plxTable"
          keep-source max-height="580" :data="tableDate" :highlightCurrentRow="false"
          :edit-config="{trigger: 'click', mode: 'cell'}" :cell-style="isEdit">
          <ux-table-column v-for="(item,index) in columns11" :key="index" :title="item.title"
            :edit-render="item.canEdit" :field="item.children?'':item.key" min-width="100" align="center"
            :fixed="item.fixed">
            <ux-table-column min-width="100" :field="items.children?'':items.key"
              v-for="(items,indexs) in item.children" :key="indexs" :title="items.title" :edit-render="items.canEdit"
              align="center">
              <template v-slot:edit="scope">
                <Input type="number" v-model="scope.row[items.key]"
                  @on-blur="saveEvent(scope.row,scope,scope.row[items.key])" @on-focus="getInputFocus($event)"></Input>
              </template>
            </ux-table-column>
          </ux-table-column>
          </ux-table-column>
        </ux-grid>
      </template>
    </div>
  </div>
</template>
<script>
  import { getReportDepartment, getCustomerReport, setTask, exportAdvanceReport } from "@/api/TApi/index.js";
  import Setting from "@/setting";

  export default {
    components: {
    },
    data() {
      return {
        departmentList: [],
        tableDate: [],
        reset: 10,
        columns11: [],
        isEditData: [],
        params: {
          date: "",
          department: "",
        }
      };
    },
    methods: {
      getInputFocus(event) {
        event.currentTarget.select();
      },
      allFun({ columns, data }) {
        const means = [] // 合计
        columns.forEach((column, columnIndex) => {
          if (columnIndex === 0) {
            means.push('合计')
          } else {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              means[columnIndex] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              // means[columnIndex] += ' 元'
              // 改变了ele的合计方式，扩展了合计场景
              // 你以为就只有上面这样玩吗？错啦，你还可以自定义样式哦
              // means[columnIndex] = '<span style="color: red">' + means[columnIndex] + '元</span>'
              means[columnIndex] = means[columnIndex]
            } else {
              means[columnIndex] = '';
            }
          }
          if (columnIndex === 3) {//月任务完成率
            means[columnIndex] = (+means[2] === 0 || +means[1] === 0) ? "0%" : ((means[2] / means[1]) * 100).toFixed(2) + "%";
          }
        })
        // 返回一个二维数组的表尾合计(不要平均值，你就不要在数组中添加)
        return [means]
      },
      isEdit(a) {
        if (this.isEditData.length) {
          for (let i in this.isEditData) {
            let data = this.isEditData[i]
            if (a._columnIndex === data._columnIndex && a._rowIndex === data._rowIndex) {
              return "color:red"
            }
          }
        }

      },

      exportData() {
        exportAdvanceReport({
          department_id: this.params.department,
          date: this.params.date ? this.$Date(this.params.date).format("YYYY-MM") : "",
        }).then(res => {
          const link = document.createElement('a')
          let blob = new Blob([res], { type: 'application/vnd.ms-excel' })
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.download = '项目任务推进表' //下载的文件名
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        })
        // window.open(`${Setting.apiBaseURL}/v1/customer/report/export-advacement-report?department_id=${this.params.department}&date=${this.params.date ? this.$Date(this.params.date).format("YYYY-MM") : ""}`)
      },
      // 点击保存
      saveEvent(row, scope, num) {
        // this.__columnIndex = null
        // this._rowIndex = null
        var reg = /^[0-9]{1}[0-9]*$/;//正整数
        let flag = reg.test(num)
        if (!flag) {
          this.isEditData.push({
            _columnIndex: scope._columnIndex,
            _rowIndex: scope._rowIndex,
          })
          this.$Message.error("请修改为正整数")
          return false
        } else {
          let index = this.isEditData.findIndex(ee => ee._columnIndex === scope._columnIndex && ee._rowIndex === scope._rowIndex)
          if (index !== -1) {
            this.isEditData.splice(index, 1)
          }
        }
        if (!this.isEditData.length) {
          if (this.$refs.plxTable.isUpdateByRow(row)) {
            // ...保存相关的逻辑（后端的呀，或者前端的呀）
            // 清除表格激活状态
            this.$refs.plxTable.clearActived().then(() => {
              // 局部保存，并将行数据恢复到初始状态（如果 第二个参数record 为空则不改动行数据，只恢复状态）
              // 你不执行这个reloadRow，代表下次进来你上面的这个if还是会执行，不然下次点击保存，还是保存成功哦！状态没改变哦
              this.$refs.plxTable.reloadRow(row, null, null)
              // 如果，假如你保存了后端给你个当前行的row，那么你需要赋值给表格行呢，你就需要把后端给你的row填到第二个参数位置
              // this.$refs.plxTable.reloadRow(row, 后端的row, null)
              // 第三个参数呢就是只改变当前行中的call单个单元格。第三个参数是row中的字段名（field属性的值）
            })
            // let index = this.tableDate.findIndex(ee => ee.id === row.id)
            // let item = this.tableDate[index]
            // item.monthly_tasks1 = (+item.first_month_tasks) + (+item.mid_month_tasks) + (+item.last_month_tasks)
            // item.monthly_completion1 = (+item.first_month_completion) + (+item.mid_month_completion) + (+item.last_month_completion)
            // item.allRate1 = (+item.monthly_completion) === 0 ? ("0%") : ((+item.monthly_completion / +item.monthly_tasks) * 100).toFixed(2) + "%"
            // this.$set(this.tableDate, index, item)

            let params = {
              first_month_tasks: + row.first_month_tasks,
              first_month_completion: +row.first_month_completion,
              mid_month_tasks: +row.mid_month_tasks,
              mid_month_completion: +row.mid_month_completion,
              last_month_tasks: +row.last_month_tasks,
              last_month_completion: +row.last_month_completion,
              last_month_completion: +row.last_month_completion,
              monthly: this.params.date ? this.$Date(this.params.date).format("YYYY-MM") : "",
              member_id: row.member_id,
              id: row.id
            }
            setTask(params).then(res => {
              // this.$Message.success('保存成功');
            }).finally(() => {
              this._getCustomerReport()
            })

          } else {
            // this.$Message.warning('保存失败，你没改变当前行的数据');
          }
        } else {
          this.$Message.error("请修改为正整数")
        }
        // 判断是否发生改变
        // console.log(this.$refs.plxTable.isUpdateByRow(row))
        // 你也可以不使用这个判断，我是给示例，没做个性化需求

      },
      _getCustomerReport() {
        let params = {
          department_id: this.params.department,
          date: this.params.date ? this.$Date(this.params.date).format("YYYY-MM") : ""
        }
        getCustomerReport(params).then(res => {
          this.tableDate = res.map(ee => {
            return {
              ...ee,
              allRate1: (+ee.monthly_completion === 0 || +ee.monthly_tasks === 0) ? ("0%") : ((+ee.monthly_completion / +ee.monthly_tasks) * 100).toFixed(2) + "%",
              monthly_tasks1: (+ee.first_month_tasks) + (+ee.mid_month_tasks) + (+ee.last_month_tasks),
              monthly_completion1: (+ee.first_month_completion) + (+ee.mid_month_completion) + (+ee.last_month_completion),
            }
          })
        })
      },
      changeParams() {
        this.judgeEdit()
        this.reset = Math.random() * 100
        this._getCustomerReport()
      },
      _getReportDepartment() {
        getReportDepartment().then((res) => {
          this.departmentList = res;
        });
      },
      judgeEdit() {
        let time = new Date().getDate()
        let month = new Date().getMonth() + 1
        let month1 = new Date(this.params.date).getMonth() + 1
        let early = false;
        let middle = false;
        let late = false;
        let year = new Date().getFullYear()
        let year1 = new Date(this.params.date).getFullYear()
        if (time <= 11 && month === month1 && year === year1) {
          early = true
        }
        if (time >= 11 && time <= 21 && month === month1 && year === year1) {
          middle = true
        }
        if ((time >= 21 && month === month1 && year === year1) || (time === 1 && (month - month1 === 1) && year === year1)) {
          late = true
        }
        this.columns11 = [
          {
            title: '姓名',
            key: 'member_name',
            align: 'center',
            minWidth: 120,
            fixed: 'left',
          },
          {
            title: '月任务',
            align: 'center',
            children: [
              {
                title: '任务数',
                key: 'monthly_tasks1',
                align: 'center',
                minWidth: 80,
              },
              {
                title: '实际完成',
                key: 'monthly_completion1',
                align: 'center',
                minWidth: 80,
              },
              {
                title: '完成率',
                key: 'allRate1',
                align: 'center',
                minWidth: 80,
              }
            ]
          },
          {
            title: '上旬任务',
            align: 'center',
            children: [
              {
                title: '任务数',
                key: 'first_month_tasks',
                align: 'center',
                minWidth: 80,
                canEdit: early,

              },
              {
                title: '实际完成',
                key: 'first_month_completion',
                align: 'center',
                minWidth: 80,
                canEdit: early,

              },
            ]
          },
          {
            title: '中旬任务',
            align: 'center',
            children: [
              {
                title: '任务数',
                key: 'mid_month_tasks',
                align: 'center',
                minWidth: 80,
                canEdit: middle,

              },
              {
                title: '实际完成',
                key: 'mid_month_completion',
                align: 'center',
                minWidth: 80,
                canEdit: middle,

              },

            ]
          },
          {
            title: '下旬任务',
            align: 'center',
            children: [
              {
                title: '任务数',
                key: 'last_month_tasks',
                align: 'center',
                canEdit: late,
                minWidth: 80,
              },
              {
                title: '实际完成',
                key: 'last_month_completion',
                align: 'center',
                canEdit: late,
                minWidth: 80,
              },

            ]
          }
        ]
      },
    },
    mounted() {
      this.params.date = this.$Date(new Date()).format("YYYY-MM")
      this.judgeEdit()
      this._getReportDepartment();
      this._getCustomerReport()
    },
    created() {
    },
  };
</script>
<style scoped>
  /deep/ input::-webkit-outer-spin-button,
  /deep/ input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }

  /deep/ input[type="number"] {
    -moz-appearance: textfield;
  }


  .rgb196 {
    background: rgb(196, 196, 196);
  }

  .bacColor317eb0 {
    background: #317eb0;
  }

  .bacColorf4984e {
    background: #f4984e;
  }
</style>